<template>
  <div class="questions-container">
    <div class="app-container">
      <el-card class="box-card" shadow="never">
        <div slot="header" class="clearfix">
          <span v-if="flage == false">试题录入</span>
          <span v-else-if="flage == true">试题修改</span>
        </div>
        <div>
          <!-- <questions-changes></questions-changes> -->
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="学科" prop="subjects">
              <el-select
                v-model="ruleForm.subjects"
                placeholder="请选择"
                @change="subjectsD"
              >
                <el-option
                  :value="item.id"
                  :label="item.subjectName"
                  v-for="(item, index) in subjectsData"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="目录" prop="directorys">
              <el-select v-model="ruleForm.directorys" placeholder="请选择">
                <el-option
                  :label="item.directoryName"
                  :value="item.creatorID"
                  v-for="(item, index) in subjectsData"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="企业" prop="company">
              <el-select v-model="ruleForm.company" placeholder="请选择">
                <el-option
                  :label="item.company"
                  :value="item.id"
                  v-for="(item, index) in companysData"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="城市" prop="cityq">
              <el-select
                v-model="ruleForm.province"
                placeholder="请选择"
                class="selectHalf selectFirst"
                @change="changeProduct()"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in provinces"
                  :key="index"
                ></el-option>
              </el-select>
              <el-select
                v-model="ruleForm.cityq"
                placeholder="请选择"
                class="selectHalf"
              >
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in citysq"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="方向" prop="orientation">
              <el-select v-model="ruleForm.orientation" placeholder="请选择">
                <el-option
                  :label="item"
                  :value="item"
                  v-for="(item, index) in directions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="题型" prop="radio">
              <el-radio
                v-model="ruleForm.radio"
                :label="item.value"
                v-for="item in questionType"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>

            <el-form-item label="难度" prop="radioTwo">
              <el-radio
                v-model="ruleForm.radioTwo"
                :label="item.value"
                v-for="item in difficulty"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>

            <el-form-item label="题干" prop="question">
              <quill-editor
                class="stem"
                v-model="ruleForm.question"
                :options="editorOption"
                @blur="checkQustion"
              >
              </quill-editor>
            </el-form-item>

            <!-- 单选按钮组的选项 -->
            <el-form-item
              label="选项:"
              class="optionRadio"
              v-if="ruleForm.radio == 1"
            >
              <div
                class="chageRadio"
                v-for="item in ruleForm.options"
                :key="item.code"
              >
                <el-radio-group
                  v-model="item.isRight"
                  @change="chanageRadioFn(item)"
                >
                  <el-radio :label="true"
                    >{{ item.code }}:
                    <el-input v-model="item.title"></el-input>
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                    >
                      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                      <span v-else>上传图片</span>
                      <i class="el-icon-circle-close"></i>
                    </el-upload>
                  </el-radio>
                </el-radio-group>
              </div>
              <el-button
                type="info"
                class="addOption"
                :disabled="ruleForm.radio == 1 ? true : false"
                >+增加选项与答案</el-button
              >
            </el-form-item>
            <!-- 多选按钮组的选项 -->
            <el-form-item
              label="选项:"
              class="optionRadio"
              v-if="ruleForm.radio == 2"
            >
              <div
                class="chageRadio"
                v-for="item in ruleForm.options"
                :key="item.code"
              >
                <el-checkbox-group
                  v-model="item.isRight"
                  @change="chanageChecked(item)"
                >
                  <el-checkbox :label="true">
                    {{ item.code }}:
                    <el-input v-model="item.title"></el-input>
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                    >
                      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                      <span v-else>上传图片</span>
                      <i class="el-icon-circle-close"></i>
                    </el-upload>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <el-button
                class="addOption"
                type="danger"
                :disabled="ruleForm.radio == 1 ? true : false"
                @click="addOptionKey"
                >+增加选项与答案</el-button
              >
            </el-form-item>
            <el-form-item label="解析视频">
              <el-input
                class="resolvVideo"
                v-model="ruleForm.resolvVideo"
              ></el-input>
            </el-form-item>

            <el-form-item label="答案解析" prop="question">
              <quill-editor
                v-model="ruleForm.daanjiexi"
                :options="editorOption"
              >
              </quill-editor>
            </el-form-item>

            <el-form-item label="题目备注">
              <el-input type="textarea" :rows="5" v-model="ruleForm.textarea">
              </el-input>
            </el-form-item>

            <el-form-item label="试题标签" class="fromitem">
              <el-select
                v-model="ruleForm.tagModelData"
                placeholder="请选择"
                multiple=""
              >
                <el-option
                  :label="item.tagName"
                  :value="item.id"
                  v-for="item in tagData"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="" class="fromitem">
              <el-button
                type="success"
                @click="submitForm('ruleForm')"
                v-if="flage == false"
                >确认提交</el-button
              >
              <el-button
                type="primary"
                @click="changeForm('ruleForm')"
                v-else-if="flage == true"
                >确认修改</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// import questionsChanges from "../components/questions-changes.vue";
import { list as listSubjects } from '@/api/hmmm/subjects.js'
import { list as listCompanys } from '@/api/hmmm/companys.js'
import { list as listDirectorys } from '@/api/hmmm/directorys.js'
import { list as tag } from '@/api/hmmm/tags.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

export default {
  name: 'questionsNew',
  components: {
    // questionsChanges,
  },
  data() {
    return {
      id: null,
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link'],
          ],
        },
        placeholder: ' ',
      },
      ruleForm: {
        // 学科
        subjects: null,
        // 目录
        directorys: null,
        // 企业
        company: null,
        // 城市
        province: '',
        // 市区
        cityq: '',
        // 方向
        orientation: '',
        // 题型
        radio: 1,
        // 难度
        radioTwo: 1,
        // 提干
        question: null,
        // 单选按钮
        radios: 1,
        // 单选按钮里的input
        radioInput: '',
        // 多选框组
        checkList: [],
        // 多选框里的input
        ckeckInput: '',
        // 视频解析
        resolvVideo: '',
        // 答案解析
        daanjiexi: null,
        // 题目备注
        textarea: '',
        // 试题标签
        tagModelData: [],

        // 选项数组
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false,
          },
        ],
      },

      rules: {
        subjects: [
          { required: true, message: '请选择活动区域', trigger: 'change' },
        ],
        company: [
          { required: true, message: '请选择活动区域', trigger: 'change' },
        ],
        cityq: [{ required: true, message: '请选择地区', trigger: 'change' }],
        orientation: [
          { required: true, message: '请选择活动区域', trigger: 'change' },
        ],
        directorys: [
          { required: true, message: '请选择活动区域', trigger: 'change' },
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'change' },
        ],
        radio: [{ required: true, message: '请填写题干', trigger: 'change' }],
        radioTwo: [
          { required: true, message: '请填写题干', trigger: 'change' },
        ],
      },
      content: null,
      content2: '',
      textarea: '',
      //学科数据
      subjectsData: [],
      //   企业数据
      companysData: [],
      //   城市数据
      provinces: [],
      //   方向数据
      directions: direction,
      //   区
      citysq: [],
      // 目录
      items: [],
      // 题型
      questionType,
      // 难度
      difficulty,
      // 试题标签数据
      tagData: [],
      // 上传图片地址
      imageUrl: '',
      Code: 68,
      flage: false,
    }
  },
  created() {
    this.subjectsList()
    this.companysList()
    this.provincesList()
    if (this.$route.query && this.$route.query.id) {
      console.log('接收到了id')
      this.flage = true
      const id = this.$route.query.id
      console.log(id)
      this.id = id
      this.getquestionsData(id)
    } else {
      this.ruleForm = {
        // 学科
        subjects: null,
        // 目录
        directorys: null,
        // 企业
        company: null,
        // 城市
        province: '',
        // 市区
        cityq: '',
        // 方向
        orientation: '',
        // 题型
        radio: 1,
        // 难度
        radioTwo: 1,
        // 提干
        question: null,
        // 单选按钮
        radios: 1,
        // 单选按钮里的input
        radioInput: '',
        // 多选框组
        checkList: [],
        // 多选框里的input
        ckeckInput: '',
        // 视频解析
        resolvVideo: '',
        // 答案解析
        daanjiexi: null,
        // 题目备注
        textarea: '',
        // 试题标签
        tagModelData: [],

        // 选项数组
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false,
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false,
          },
        ],
      }
      console.log('没有接收到id')
    }
  },
  watch: {},
  methods: {
    //   获取学科数据
    async subjectsList() {
      const { data } = await listSubjects()
      this.subjectsData = data.items
      console.log(this.subjectsData, 1112)
    },
    //获取企业数据
    async companysList() {
      const { data } = await listCompanys()
      this.companysData = data.items
      console.log(1, this.companysData)
    },
    provincesList() {
      const data = provinces()
      this.provinces = data
      console.log(data)
    },

    changeProduct() {
      const data = citys(this.ruleForm.province)
      this.citysq = data
    },
    // 确认添加按钮
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const data = {
            subjectID: this.ruleForm.subjects,
            catalogID: this.ruleForm.directorys,
            enterpriseID: this.ruleForm.company,
            province: this.ruleForm.province,
            city: this.ruleForm.cityq,
            direction: this.ruleForm.orientation,
            questionType: this.ruleForm.radio + '',
            difficulty: this.ruleForm.radioTwo + '',
            question: this.ruleForm.question,
            options: this.ruleForm.options,
            videoURL: this.ruleForm.resolvVideo,
            answer: this.ruleForm.daanjiexi,
            remarks: this.ruleForm.textarea,
            tags: this.ruleForm.tagModelData.join(','),
          }
          console.log(data, 22)
          const res = await add(data)

          if (res.status === 200) {
            this.$message.success('试题录入成功')
            this.$router.push('/questions/list')
          } else {
            this.$message.error('试题录入失败')
          }
        } else {
          this.$message.error('请填写表格必填项')
          return false
        }
      })
      console.log(this.ruleForm, 1)
    },
    // 修改按钮
    changeForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const data = {
            id: this.id,
            subjectID: this.ruleForm.subjects,
            catalogID: this.ruleForm.directorys,
            enterpriseID: this.ruleForm.company,
            province: this.ruleForm.province,
            city: this.ruleForm.cityq,
            direction: this.ruleForm.orientation,
            questionType: this.ruleForm.radio + '',
            difficulty: this.ruleForm.radioTwo + '',
            question: this.ruleForm.question,
            options: this.ruleForm.options,
            videoURL: this.ruleForm.resolvVideo,
            answer: this.ruleForm.daanjiexi,
            remarks: this.ruleForm.textarea,
            tags: this.ruleForm.tagModelData.join(','),
          }
          console.log(data, 22)
          const res = await update(data)
          console.log('求改', res)
          if (res.status === 200) {
            this.$message.success('试题修改成功')
            this.$router.push('/questions/list')
          } else {
            this.$message.error('试题修改失败')
          }
        } else {
          this.$message.error('请填写表格必填项')
          return false
        }
      })
      console.log(this.ruleForm, 1)
    },
    //学科改变触发事件
    async subjectsD() {
      this.ruleForm.directorys = null
      const { data } = await listDirectorys({
        subjectID: this.ruleForm.subjects,
      })
      console.log(data, 22222)
      this.items = data.items
      const res = await tag({
        subjectID: this.ruleForm.subjects,
      })
      this.tagData = res.data.items
      console.log(this.tagData, 112233)
    },
    checkQustion() {
      //失去焦点事件
      this.$refs['ruleForm'].validateField('question')
    },
    // 选项按钮改变时
    chanageRadioFn(item) {
      this.ruleForm.options.forEach((item) => {
        item.isRight = false
      })
      item.isRight = true
    },
    chanageChecked(item) {
      item.isRight = true
    },
    // 上传图片成功触发事件
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log(110, this.imageUrl)
    },
    addOptionKey() {
      var a = String.fromCharCode(++this.Code)

      const obj = {
        code: a,
        title: '',
        img: '',
        isRight: false,
      }
      this.ruleForm.options.push(obj)
    },
    // 接收到id的时候触发事件
    async getquestionsData(id) {
      try {
        const { data } = await detail({ id: id })
        console.log('通过传id获取到的数据', data)
        this.ruleForm.subjects = data.subjectID
        this.ruleForm.directorys = data.catalogID
        this.ruleForm.company = data.enterpriseID
        this.ruleForm.province = data.province
        this.ruleForm.cityq = data.city
        this.ruleForm.orientation = data.direction
        this.ruleForm.radio = Number(data.questionType)
        this.ruleForm.radioTwo = Number(data.difficulty)
        this.ruleForm.question = data.question
        this.ruleForm.options = data.options
        this.ruleForm.resolvVideo = data.videoURL
        this.ruleForm.daanjiexi = data.answer
        this.ruleForm.textarea = data.remarks
        this.ruleForm.tagModelData = data.tags.split(',')
      } catch (err) {
        console.log(err)
      }
    },
  },
}
</script>

<style scoped lang='less'>
.questions-container {
  .el-select {
    width: 400px;
  }
  .selectHalf {
    width: 195px;
  }
  .selectFirst {
    margin-right: 10px;
  }

  /deep/.ql-container {
    height: 200px;
  }

  .getPhoneBtn {
    position: relative;
    height: 50px;
    border: 1px gainsboro dashed;
    margin-left: 5px;
    div {
      position: absolute;
      top: -5px;
      right: -5px;
    }
  }
  .optionRadio {
    .el-radio {
      display: block;
      margin-bottom: 10px;
      .el-input--medium {
        width: 300px;
      }
    }
    .addOption {
      // background-color: #c0c4cc;
      color: white;
      margin-top: 20px;
    }
  }
  .el-input--medium {
    width: 400px;
  }
  .testTitle {
    display: block;
    margin-bottom: 15px;
  }
  .chageRadio {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .el-radio {
      margin: 0;
      margin-right: 10px;
    }
    .el-input {
      width: 300px;
    }

    // 上传图片css
    /deep/ .avatar-uploader .el-upload {
      width: 80px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: absolute;
      left: 350px;
      top: -5px;

      img {
        width: 100%;
        height: 100%;
        display: block;
      }
      span {
        font-size: 12px;
        color: #8c939d;
      }
      i {
        position: absolute;
        top: -5px;
        right: -5px;
      }
    }
  }
}
</style>
